package com.ndp.fb.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtils {

    private static final CloseableHttpClient httpClient;
    public static final String CHARSET = "UTF-8";

    static {
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(30000)
                .setSocketTimeout(15000)
                .build();
        httpClient = HttpClientBuilder.create()
                .setDefaultRequestConfig(config)
                .build();
    }

    public static String httpGet(String url) {
        return httpGet(url, null, CHARSET);
    }

    public static String httpGet(String url, Map<String, String> params) {
        return httpGet(url, params, CHARSET);
    }

    public static String httpPost(String url) {
        return httpPost(url, null, CHARSET);
    }

    public static String httpPost(String url, Map<String, String> params) {
        return httpPost(url, params, CHARSET);
    }


    /**
     * @param url    url地址
     * @param params 参数,编码之前的参数
     * @return
     */
    public static String httpGet(String url, Map<String, String> params, String charset) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
            }
            HttpGet httpget = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpget);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpget.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            return getResult(response, entity);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String getResult(CloseableHttpResponse response, HttpEntity entity) throws IOException {
        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, CHARSET);
        }
        EntityUtils.consume(entity);
        response.close();
        return result;
    }

    /**
     * @param url    url地址
     * @param params 参数,编码之前的参数
     * @return
     */
    public static String httpPost(String url, Map<String, String> params, String charset) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        try {
            List<NameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
            }
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs, charset);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            return getResult(response, entity);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /** 
     * HttpClient PUT请求 
     * @author huang 
     * @date 2013-4-10 
     * @return 
     * @throws UnsupportedEncodingException 
     */  
    public static String httpPut(String uri,String jsonObj){  

        try{  
            HttpPut putMethod = new HttpPut(uri);  
            putMethod.addHeader( "Content-Type","application/json" );  
            StringEntity params =new StringEntity(jsonObj);
            putMethod.setEntity(params);  
            CloseableHttpResponse response = httpClient.execute(putMethod);
//            log.info(statusCode);  
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
            	putMethod.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            return getResult(response, entity);
        }catch(Exception e){  
        	 throw new RuntimeException(e);
        } 
    }
}